package com.cloud.server.hoock;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.http.MediaType;

import com.cloud.common.tools.RestClientUtil;
import com.cloud.server.properties.CloudServerPorperties;

public class ServerRegistar implements ApplicationListener<ContextRefreshedEvent> {

	private CloudServerPorperties cloudServerPorperties;

	public ServerRegistar(CloudServerPorperties cloudServerPorperties) {
		super();
		this.cloudServerPorperties = cloudServerPorperties;
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
			System.out.println("程序启动");
			Map<String, String> condition = new HashMap<String, String>();
			condition.put("appName", cloudServerPorperties.getAppName());
			try {
				condition.put("serverUrl","http://".concat(InetAddress.getLocalHost().getHostAddress()).concat(":").concat(String.valueOf(cloudServerPorperties.getPort()).concat("/")));
			} catch (UnknownHostException e1) {
				e1.printStackTrace();
			}
			try {
				String path = cloudServerPorperties.getServerUrl()+"/regist";
				System.out.println("regist "+RestClientUtil.httpClientByPost(path, condition, String.class, MediaType.APPLICATION_JSON_UTF8));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
